package cn._2dland.http;

import java.util.HashMap;
import java.util.Map;

import cn._2dland.http.method.HttpMethod;

/**
 * Simple HttpClient For GAE/J
 */
public class HttpClient {
	private HttpClientParams params;
	private HttpCookie cookie = new HttpCookie();
	
	/** 附加请求头 */
	private Map<String, String> headers = null;

	public HttpClient() {
		this(new HttpClientParams());
	}

	public HttpClient(HttpClientParams params) {
		this.params = params;
		headers = new HashMap<String, String>();
	}

	/**
	 * 获取客户端参数
	 * @return
	 */
	public HttpClientParams getClientParams() {
		return this.params;
	}

	/**
	 * 添加附加的请求头
	 * 
	 * @param name
	 * @param value
	 */
	public void addHeader(String name, String value) {
		headers.put(name, value);
	}

	/**
	 * 执行请求
	 * 
	 * @param method 请求对象
	 * @return 服务器响应码
	 */
	public int executeMethod(HttpMethod method) {
		int respCode = 0;
		try {
			// 设置客户端配置
			method.getMethodParams().merge(params);
			// 设置cookie
			if(!cookie.isEmpty())
				method.addRequestHeader("Cookie", cookie.toString());
			// 设置附加请求头
			if(headers != null && !headers.isEmpty()) {
				for(String name : headers.keySet()) {
					String value = headers.get(name);
					method.addRequestHeader(name, value);
				}
			}
			// 执行请求
			respCode = method.execute();
			// 保存cookie
			cookie.addCookies(method.getCookies());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return respCode;
	}
}
